<?php
declare(strict_types=1);
/**
 *  用户地址表
 * Date: 2021年3月4日
 * Time: 18:06:03
 */

namespace App\Model\BbcModel;

use App\Model\BaseModel\BaseBbcModel;
use Service\Code\Normal;
use Service\ExtraService\TaskWorker;

class Address extends BaseBbcModel {

    public $table = 'ly_address';

    protected $fillable = [
        'id', 'cd', 'md', 'df', 'sid', 'mid', 'true_name', 'idcard', 'tel_phone', 'mobile', 'province', 'city', 'area',
        'area_info','address','is_default','card_front','card_back',
    ];

    /**
     * 新增收货地址
     * @param array
     * @access   public
     * @return   array
     */
    public function newAddress(array $param = []): array {
        $res = $this->validate($param);
        if ($res['code'] != Normal::SUC) {
            return $res;
        }

        $param['city'] = empty($param['city']) ? 0 : $param['city'];
        $param['area'] = empty($param['area']) ? 0 : $param['area'];
        if (isset($param['idcard']) && !empty($param['idcard'])) {
            $param['idcard'] = strtoupper($param['idcard']);
            $idcardauth      = $this->idcardauth(["true_name" => $param['true_name'], "idcard" => $param['idcard'], 'cid' => $param['cid']]);
            if ($idcardauth['code'] != Normal::SUC) {
                return $idcardauth;
            }
        }
        $add_data = [
            'mid'        => $param['mid'],
            'true_name'  => $param['true_name'],
            'idcard'     => $param['idcard'] ?? '',
            'mobile'     => $param['mobile'],
            'province'   => intval($param['province']),
            'city'       => intval($param['city']),
            'area'       => intval($param['area']),
            'address'    => $param['address'],
            'card_front' => $param['card_front'] ?? '',
            'card_back'  => $param['card_back'] ?? '',
            'is_default' => !empty($param['is_default']) ? 1 : 0,
            'cd'         => time(),
        ];
        $res      = $this->add($add_data);
        if (!$res) {
            return Normal::returnCode(Normal::FAIL, '新增失败');
        }
        //若新增的地址为默认地址
        if ($add_data['is_default'] == 1) {
            $where = [
                ['mid', '=', $param['mid']],
                ['id', '<>', $res],
                ['is_default', '=', 1],
            ];

            $this->edit($where, ['is_default' => 0]);
        }
        return Normal::returnCode(Normal::SUC, '新增成功', $res);

    }

    /**
     * 验证新增
     * @param array $parma
     * @access   protected
     * @return   array
     */
    protected function validate(array $param = []): array {
        if (empty($param['mid'])) {
            return Normal::returnCode(Normal::FAIL, 'expect param mid');
        }

        $member = Member::instance()->info(['mid' => $param['mid']]);

        if (empty($member)) {
            return Normal::returnCode(Normal::FAIL, '用户不存在');
        }

        if (empty($param['true_name'])) {
            return Normal::returnCode(Normal::FAIL, '请输入收货人');
        }

        if (empty($param['mobile'])) {
            return Normal::returnCode(Normal::FAIL, '请输入收货人手机');
        }

        if (empty($param['province'])) {
            return Normal::returnCode(Normal::FAIL, '请选择省');
        }
        if (empty($param['address'])) {
            return Normal::returnCode(Normal::FAIL, '请输入详细地址');
        }
        return Normal::returnCode(Normal::SUC, '验证通过');
    }

    /**
     * 实名认证收货地址
     * @param array $param
     * @access   public
     * @return   array
     */
    public function idcardauth(array $param = []): array {

        //获取配置
        $auth = ConfigChannel::instance()->getConfig(['code' => 'id_auth', 'cid' => $param['cid']]);
        $auth = $auth['data']['value'];

        //请求二要素
        $url  = 'https://api.253.com/open/idcard/id-card-auth';
        $data = [
            'appId'  => $auth['appId'],
            'appKey' => $auth['appKey'],
            'name'   => $param['true_name'],
            'idNum'  => $param['idcard']
        ];

        $parameter = [
            [
                'tag'    => 'id_card_auth',
                'url'    => $url,
                'data'   => $data,
                'method' => 'post',
                'format' => 'x-www-form-urlencoded',
                'header' => [],
            ],
        ];
        $resTask   = TaskWorker::instance()->addTask($parameter);
        $resTask   = current($resTask);
        $response  = @json_decode($resTask['response']['result'], true);

        if ($response['code'] != 200000) {
            return Normal::returnCode(Normal::FAIL, '实名认证失败' . $response['message']);
        }

        if ($response['data']['result'] != '01') {
            return Normal::returnCode(Normal::FAIL, '实名认证信息' . $response['data']['remark'] . ',请确认信息');
        }

        return Normal::returnCode(Normal::SUC, '认证成功');
    }
}